package com.ztesoft.ossup.report.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.ossup.report.dao.ChartRepository;
import com.ztesoft.ossup.report.dao.JdbcTemplateDao;
import com.ztesoft.ossup.report.dao.ReportColumnRepo;
import com.ztesoft.ossup.report.dao.ReportRepository;
import com.ztesoft.ossup.report.dao.ReportSubRepo;
import com.ztesoft.ossup.report.domain.BaseChart;
import com.ztesoft.ossup.report.domain.BaseChartData;
import com.ztesoft.ossup.report.domain.BasePieChartData;
import com.ztesoft.ossup.report.domain.ReportChart;
import com.ztesoft.ossup.report.domain.Report;
import com.ztesoft.ossup.report.domain.ReportSub;

@Service("chartService")
public class ChartService {
	@Autowired
	JdbcTemplateDao jdbcTemplateDao;

	@Autowired
	ReportRepository reportRepository;

	@Autowired
	ChartRepository chartRepository;

	@Autowired
	ReportSubRepo reportSubRepo;

	public Map<String, Object> getLineChartData() {
		Map<String, Object> map = new HashMap<>();
		BaseChart chart = new BaseChart();

		// 柱状图、折线图数据
		List<BaseChartData> series = new ArrayList<>();
		BaseChartData sery1 = new BaseChartData();
		sery1.label = "北京";
		sery1.backgroundColor = "rgba(70,178,241,1)";
		sery1.data = new Double[] { 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 };
		series.add(sery1);

		BaseChartData sery2 = new BaseChartData();
		sery2.label = "天津";
		sery2.backgroundColor = "rgba(220,120,220,1)";
		sery2.data = new Double[] { -0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5 };
		series.add(sery2);

		BaseChartData sery3 = new BaseChartData();
		sery3.label = "上海";
		sery3.backgroundColor = "rgba(220,120,120,1)";
		sery3.data = new Double[] { -0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0 };
		series.add(sery3);

		BaseChartData sery4 = new BaseChartData();
		sery4.label = "福州";
		sery4.backgroundColor = "rgba(80,20,90,1)";
		sery4.data = new Double[] { 3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8 };
		series.add(sery4);

		// 饼图各个部分名称数据
		String[] pieLabels = { "福州", "北京", "天津", "上海", "深圳" };
		chart.setPieChartLabels(pieLabels);

		// 饼图数据
		List<BasePieChartData> pieChartDatas = new ArrayList<>();
		BasePieChartData pieData = new BasePieChartData();
		pieData.data = new Double[] { 1.0, 2.0, 3.0, 4.0, 5.0 };
		pieData.backgroundColor = new String[] { "#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360" };
		pieData.label = "Dataset 1";
		pieChartDatas.add(pieData);
		chart.setPieChartDatas(pieChartDatas);

		String[] months = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
				"Dec" };
		chart.setxAxesLabels(months);
		chart.setxAxesTitle("月份");// x轴标题
		chart.setyAxesTitle("温度 (°C)");// y轴标题
		chart.setChartDatas(series);// y轴数据
		chart.setTypes(new String[] { "101", "102", "103" });
		chart.setTitle("月平均气温图");
		chart.setTitleForPie("各部分占比情况");
		chart.setSubTitle("来源：世界天气网");
		map.put("baseChart", chart);
		return map;
	}

	public String randomColor(String alpha) {
		return "rgba(" + randomColorFactor() + "," + randomColorFactor() + "," + randomColorFactor() + "," + alpha
				+ ")";
	};

	public int randomColorFactor() {
		return (int) Math.round(Math.random() * 255);
	};

	public Map<String, Object> getChartData(Long reportId,Map<String, String> params) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("reportId", reportId.toString());
		paramMap.putAll(params);
		List<Map<String, Object>> dataMaps = getReportData(paramMap);
		BaseChart baseChart = new BaseChart();//页面显示配置
		ReportChart chart = chartRepository.findByReportId(reportId);

		Map<String, Object> map = new HashMap<>();
		

		baseChart.setxAxesTitle(chart.getxAxesTitle());// x轴标题
		baseChart.setyAxesTitle(chart.getyAxesTitle());// y轴标题
		baseChart.setTitle(chart.getTitle());
		baseChart.setTitleForPie(chart.getTitleForPie());
		baseChart.setSubTitle(chart.getSubTitle());

		List<ReportSub> types = reportSubRepo.findAllByReportId(reportId);
		String[] typeStrs = new String[types.size()];
		for (int i = 0; i < typeStrs.length; i++) {
			typeStrs[i] = types.get(i).getType();
		}

		baseChart.setTypes(typeStrs);

		String xTitleKey = "";
		if (!chart.getxDataKeys().contains(";")) {
			xTitleKey = chart.getxDataKeys();
		} else {
			baseChart.setxAxesLabels(chart.getxDataKeys().split(";"));
		}

		String[] yDataKeys = chart.getyDataKeys().split(";");

		String[] bgColors = new String[yDataKeys.length];
		for (int i = 0; i < bgColors.length; i++) {
			bgColors[i] = randomColor("0.6");
		}
		baseChart.setxAxesLabels(new String[dataMaps.size()]);
		baseChart.setChartDatas(new ArrayList<BaseChartData>());
		baseChart.setPieChartDatas(new ArrayList<BasePieChartData>());

		String[] bgColorsForPie = new String[dataMaps.size()];
		for (int k = 0; k < bgColorsForPie.length; k++) {
			bgColorsForPie[k] = randomColor("0.6");
		}

		for (int i = 0; i < yDataKeys.length; i++) {
			BaseChartData chartData = new BaseChartData();
			chartData.data = new Double[dataMaps.size()];
			int j = 0;
			for (Map<String, Object> dataMap : dataMaps) {
				if (dataMap.get(yDataKeys[i]) == null) {
					chartData.data[j] = 0.0;
				} else {
					chartData.data[j] = ((BigDecimal) dataMap.get(yDataKeys[i])).doubleValue();
				}

				baseChart.getxAxesLabels()[j] = String.valueOf(dataMap.get(xTitleKey));
				j++;
			}
			chartData.label = String.valueOf(yDataKeys[i]);
			chartData.fill = false;
			chartData.backgroundColor = bgColors[i];

			BasePieChartData pieChartData = new BasePieChartData();

			pieChartData.backgroundColor = bgColorsForPie;
			pieChartData.data = chartData.data;
			pieChartData.label = String.valueOf(yDataKeys[i]);

			baseChart.getPieChartDatas().add(pieChartData);
			baseChart.setPieChartLabels(baseChart.getxAxesLabels());
			baseChart.getChartDatas().add(chartData);
		}

		map.put("baseChart", baseChart);
		return map;
	}

	public Map<String, Object> getPieChartData() {
		return getLineChartData();
	}

	@Autowired
	ReportColumnRepo reportColumnRepo;

	@SuppressWarnings("rawtypes")
	public List<Map<String, Object>> getReportData(Map<String, Object> paramMap) {
		List<Map<String, Object>> dataList = null;
//		List<ReportColumn> reportColList = null;
		try {
			String reportId = (String) paramMap.get("reportId");
//			reportColList = reportColumnRepo.findByReportId(Long.valueOf(reportId));
			Report report = reportRepository.findOne(Long.valueOf(reportId));
			String dataSql = report.getSql();
			// }
			if (dataSql != null && !dataSql.equals("")) {
				Iterator itera = paramMap.entrySet().iterator();
				while (itera.hasNext()) {
					// _logger.info("---------Map数据----------");
					Map.Entry entry = (Map.Entry) itera.next();
					String key = (String) entry.getKey();
					String value = (String) entry.getValue();
					if (dataSql.indexOf("#" + key + "#") > -1 && !value.equals("") && value != null) {
						dataSql = dataSql.replaceAll("#" + key + "#", "'" + value + "'");
					}
				}
				// dataSql = dataSql.replaceAll("where city_code =#cityName#",
				// "");
				dataList = jdbcTemplateDao.getData(dataSql);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Map retMap = new HashMap();
		// retMap.put("reportColList", reportColList);
		// retMap.put("reportDataList", dataList);
		return dataList;
	}

}
